<template>
  <div class="sms-signature-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">短信签名</h2>
      </div>
    </div>

    <!-- 信息提示条 -->
    <el-alert
      title="根据工信部及各级运营商的要求，短信发送前需完成签名备案。由于各地运营商的审核进度不同，签名制报备通常需要 3-7 个工作日。建议您在报备完成后再尝试发送，先小批量测试短信效果再说，确保成功率符合预期后再正式发送业务短信。"
      type="info"
      show-icon
      :closable="true"
      class="info-alert"
    />

    <!-- 标签页 -->
    <div class="tab-container">
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane label="签名管理" name="signature"></el-tab-pane>
        <el-tab-pane label="资质管理" name="qualification"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 签名管理说明 -->
    <div class="signature-instructions" v-if="activeTab === 'signature'">
      <ol>
        <li>签名审批1-4个小时内审完成，工作时间：9:00-21:00（法定节假日顺延），建议您尽量在18:00前提交申请。</li>
        <li>了解更多短信签名审核规范请<a href="#" class="link-text">飞链引擎</a></li>
        <li>飞链引擎短信服务严禁将该业务金融类信息和赌博、诈骗、色情、暴力等违法信息，如您的飞链引擎账号一旦涉及违规发送以上内容，飞链引擎将根据服务协议对您采取停机服务，封号等措施，并移交公安机关处理（包括但不限于：飞链引擎签名认证信息等）并移交公安机关处理。</li>
        <li>当前页面最多支持显示1000个短信签名，如需查看更多请添加筛选条件或使用搜索框。</li>
      </ol>
    </div>

    <!-- 签名管理内容 -->
    <div v-if="activeTab === 'signature'">
      <!-- 搜索和筛选工具栏 -->
      <div class="filter-toolbar">
        <div class="left-section">
          <el-input
            v-model="queryParams1.signatureName"
            placeholder="请输入签名名称"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery1"
          />
          <el-select v-model="queryParams1.auditStatus" placeholder="请选择审核状态" clearable >
            <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <el-select v-model="queryParams1.certificationId"  filterable placeholder="请选择资质" clearable>
            <el-option v-for="item in certificationList" :key="item.applyId" :label="item.enterpriseName"
                       :value="item.applyId"></el-option>
          </el-select>
        </div>
        <div class="right-section">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateSignature" class="custom-button primary-button">
            新增签名
          </el-button>
        </div>
      </div>

      <!-- 签名表格 -->
      <el-table
        :data="signatures"
        style="width: 100%"
        :header-cell-style="tableHeaderStyle"
        border
        class="custom-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="签名ID" prop="signatureId" min-width="120"></el-table-column>
        <el-table-column label="签名种类" align="center" prop="signatureType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.signature_type" :value="scope.row.signatureType"/>
          </template>
        </el-table-column>
        <el-table-column label="签名名称" prop="signatureName" min-width="120"></el-table-column>
        <el-table-column label="签名内容" prop="signatureContent" min-width="120"></el-table-column>
        <el-table-column label="用途描述" prop="purposeDescription" min-width="150"></el-table-column>
        <el-table-column label="资质ID" prop="certificationId" min-width="150"></el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.auditStatus)"
              size="small"
              class="custom-tag"
            >
              {{ getStatusText(scope.row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" class="action-button" @click="handleViewSignature(scope.row)">查看</el-button>
<!--            <el-button type="text" size="small" class="action-button" @click="handleCopySignature(scope.row)">复制</el-button>-->
            <el-button type="text" size="small" class="action-button" @click="handleDeleteSignature(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据状态 -->
      <div class="empty-state" v-if="!signatures || signatures.length === 0">
        <img src="/placeholder.svg?height=100&width=100" alt="暂无数据" class="empty-image">
        <p class="empty-text">暂无数据</p>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="signatures && signatures.length > 0">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="custom-pagination"
        />
      </div>
    </div>

    <!-- 资质管理内容 -->
    <div v-if="activeTab === 'qualification'">
      <!-- 搜索和筛选工具栏 -->
      <div class="filter-toolbar">
        <div class="left-section">
          <el-input
            v-model="queryParams2.enterpriseName"
            placeholder="请输入企业名称"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery2"
          />
          <el-select v-model="queryParams2.auditStatus" placeholder="请选择审核状态" clearable style="width: 220px">
              <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </div>
        <div class="right-section">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateResource" class="custom-button primary-button">
            新增资质
          </el-button>
        </div>
      </div>

      <!-- 资质表格 -->
      <el-table
        :key="`certification-table-${activeTab}-${certificationList.length}`"
        v-loading="loading"
        :data="certificationList"
        style="width: 100%"
        :header-cell-style="tableHeaderStyle"
        border
        class="custom-table">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="申请单号" prop="applyId" align="center" width="180" />
        <el-table-column label="客户名称" prop="smsName" align="left" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="企业名称" prop="enterpriseName" align="left" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="统一社会信用代码" prop="bizLicenseNumber" align="left" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="资质名称" prop="qualificationName" align="left" min-width="120" :show-overflow-tooltip="true" />

        <el-table-column label="法人姓名" align="center" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.legalPersonName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="经办人姓名" align="center" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.operatorName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="责任人姓名" align="center" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.responsibleName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.createdAt ? scope.row.createdAt.substring(0, 10) : '' }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" width="90">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" prop="auditRemarks" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column label="审核时间" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.auditTime ? scope.row.auditTime.substring(0, 10) : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" class="action-button" @click="handleDetail(scope.row)">查看</el-button>
            <el-button type="text" size="small" class="action-button" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="small" class="action-button" @click="handleReapplyResource(scope.row)">修改</el-button>
            <el-button type="text" size="small" class="action-button" @click="handleQuickCopy(scope.row)">快速复制</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 资质表格数据 -->
      <div v-if="certificationList && certificationList.length > 0" class="table-footer">
        <span class="page-info">显示第 {{ (currentPage2 - 1) * pageSize2 + 1 }} - {{ Math.min(currentPage2 * pageSize2, total2) }} 条，共 {{ total2 }} 条</span>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage2"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
          class="custom-pagination"
        ></el-pagination>
      </div>
    </div>

    <!-- 新建签名对话框 -->
    <el-dialog
      :title="formMode === 'add' ? '新增签名' : (formMode === 'edit' ? '编辑签名' : '签名详情')"
      :visible.sync="signatureDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      custom-class="custom-dialog"
    >
      <el-form :model="signatureForm" :rules="signatureRules" ref="signatureForm" label-width="100px" class="custom-form">
        <el-form-item label="签名名称" prop="signatureName" required>
          <el-input
            v-model="signatureForm.signatureName"
            placeholder="请输入签名名称"
            :disabled="formMode === 'view'"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="签名类型" prop="signatureType" required>
          <el-select v-model="signatureForm.signatureType" placeholder="请选择签名类型" style="width: 100%" :disabled="formMode === 'view'" class="custom-select">
            <el-option label="企业" value="1"></el-option>
            <el-option label="产品" value="2"></el-option>
            <el-option label="网站" value="3"></el-option>
            <el-option label="APP" value="4"></el-option>
            <el-option label="公众号" value="5"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="签名内容" prop="signatureContent" required>
          <el-input
            v-model="signatureForm.signatureContent"
            placeholder="签名内容"
            maxlength="25"
            show-word-limit
            :disabled="formMode === 'view'"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="用途描述" prop="purposeDescription" required>
          <el-input
            type="textarea"
            v-model="signatureForm.purposeDescription"
            :rows="5"
            placeholder="请输入该签名的使用场景"
            :disabled="formMode === 'view'"
            class="custom-textarea"
          ></el-input>
        </el-form-item>

        <el-form-item label="网站地址" prop="websiteUrl">
          <el-input
            v-model="signatureForm.websiteUrl"
            placeholder="请输入企业官网链接"
            :disabled="formMode === 'view'"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="关联资质" prop="certificationId">
          <el-select
            v-model="signatureForm.certificationId"
            style="width: 100%;"
            filterable
            placeholder="资质ID"
            clearable
            :disabled="formMode === 'view'"
          >
            <el-option
              v-for="item in certificationList"
              :key="item.applyId"
              :label="item.enterpriseName"
              :value="item.applyId"
            ></el-option>
          </el-select>
        </el-form-item>

        <div class="additional-files" v-if="formMode !== 'view'">
          <p class="section-title">更多资料</p>
          <el-upload
            class="upload-demo custom-upload"
            action="#"
            :http-request="handleFileUpload"
            :file-list="additionalFiles"
            :on-remove="handleFileRemove"
            multiple
          >
            <el-button size="small" type="primary" icon="el-icon-upload2" class="custom-button">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持上传jpg、png、jpeg格式的图片，每张图片不大于2MB</div>
          </el-upload>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="signatureDialogVisible = false" class="custom-button">关 闭</el-button>
        <el-button v-if="formMode !== 'view'" type="primary" @click="submitSignatureForm" class="custom-button primary-button">提 交</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="资质认证详情"
      :visible.sync="detailOpen"
      width="800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      @closed="handleDetailClosed">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请单号">{{ detail.applyId }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="detail.auditStatus === 'pending'" type="warning">待审核</el-tag>
          <el-tag v-else-if="detail.auditStatus === 'approved'" type="success">审核中</el-tag>
          <el-tag v-else-if="detail.auditStatus === 'successful'" type="success">审核成功</el-tag>
          <el-tag v-else-if="detail.auditStatus === 'rejected'" type="danger">审核失败</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="企业名称" :span="2">{{ detail.enterpriseName }}</el-descriptions-item>
        <el-descriptions-item label="资质名称">{{ detail.qualificationName }}</el-descriptions-item>
        <el-descriptions-item label="证件类型">
          <span v-if="detail.bizLicenseType === 'business_license'">营业执照</span>
          <span v-else-if="detail.bizLicenseType === 'organization_code'">社会信用代码证书</span>
          <span v-else-if="detail.bizLicenseType === 'public_institution_cert'">事业单位法人证书</span>
        </el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码" :span="2">{{ detail.bizLicenseNumber }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">法人信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="法人姓名">{{ detail.legalPersonName }}</el-descriptions-item>
        <el-descriptions-item label="法人身份证号">{{ detail.legalPersonIdcard }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">经办人信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="经办人姓名">{{ detail.operatorName }}</el-descriptions-item>
        <el-descriptions-item label="经办人身份证号">{{ detail.operatorIdcard }}</el-descriptions-item>
        <el-descriptions-item label="经办人手机号">{{ detail.operatorPhone }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">责任人信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="责任人姓名">{{ detail.responsibleName }}</el-descriptions-item>
        <el-descriptions-item label="责任人身份证号">{{ detail.responsibleIdcard }}</el-descriptions-item>
        <el-descriptions-item label="责任人手机号">{{ detail.responsiblePhone }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">其他信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="生效签名范围">{{ detail.authorizedSignatures }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detail.updatedAt }}</el-descriptions-item>
      </el-descriptions>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">取 消</el-button>
              </div>
    </el-dialog>

    <el-dialog
      :title="
        resourceFormMode === 'add' ? '新建资质信息' :
        resourceFormMode === 'edit' ? '编辑资质信息' :
        resourceFormMode === 'reapply' ? '重新申请资质' :
        '资质详情'
      "
      :visible.sync="resourceDialogVisible"
      width="650px"
      :close-on-click-modal="false"
      custom-class="custom-dialog">
      <el-form ref="resourceForm" :model="resourceForm" :rules="resourceRules"   label-width="160px" v-if="resourceDialogVisible">
        <el-tabs v-model="activeTabcCert">
          <el-tab-pane label="基本信息" name="base">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="resourceForm.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>

            <el-form-item label="资质名称" prop="qualificationName">
              <el-input v-model="resourceForm.qualificationName" placeholder="请输入资质名称" />
        </el-form-item>

            <el-form-item label="证件类型" prop="bizLicenseType">
              <el-select v-model="resourceForm.bizLicenseType" placeholder="请选择证件类型" style="width: 100%">
                <el-option label="营业执照" value="business_license" />
                <el-option label="事业单位法人证书" value="1" />
                <el-option label="社会团体法人登记证书" value="2" />
                <el-option label="民办非企业单位登记证书" value="3" />
                <el-option label="其他" value="4" />
              </el-select>
        </el-form-item>

            <el-form-item label="社会信用代码" prop="bizLicenseNumber">
              <el-input v-model="resourceForm.bizLicenseNumber" placeholder="请输入统一社会信用代码" />
        </el-form-item>


            <!--                <el-form-item label="审核状态" prop="auditStatus">-->
            <!--                  <el-select v-model="form.auditStatus" placeholder="请选择审核状态" style="width: 100%">-->
            <!--                    <el-option label="待审核" value="0" />-->
            <!--                    <el-option label="审核通过" value="1" />-->
            <!--                    <el-option label="审核拒绝" value="2" />-->
            <!--                  </el-select>-->
            <!--                </el-form-item>-->

            <el-form-item label="法人姓名" prop="legalPersonName">
              <el-input v-model="resourceForm.legalPersonName" placeholder="请输入法人姓名" />
        </el-form-item>
            <el-form-item label="营业执照" prop="bizLicenseImage">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleBizLicenseSuccess"
                :file-list="bizLicenseFileList"
                :headers="headers"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
              </el-upload>
        </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="经办人信息" name="operator">

            <el-form-item label="经办人姓名" prop="operatorName">
              <el-input v-model="resourceForm.operatorName" placeholder="请输入经办人姓名" />
        </el-form-item>

            <el-form-item label="经办人身份证号" prop="operatorIdcard">
              <el-input v-model="resourceForm.operatorIdcard" placeholder="请输入经办人身份证号" />
        </el-form-item>


            <el-form-item label="经办人手机号" prop="operatorPhone">
              <el-input v-model="resourceForm.operatorPhone" placeholder="请输入经办人手机号" />
        </el-form-item>


            <el-form-item label="经办人身份证正面" prop="operatorIdcardFront">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleOperatorFrontSuccess"
                :file-list="operatorFrontFileList"
                :headers="headers"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
              </el-upload>
            </el-form-item>


            <el-form-item label="经办人身份证背面" prop="operatorIdcardBack">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleOperatorBackSuccess"
                :file-list="operatorBackFileList"
                :headers="headers"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
              </el-upload>
        </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="责任人信息" name="responsible">

            <el-form-item label="责任人姓名" prop="responsibleName">
              <el-input v-model="resourceForm.responsibleName" placeholder="请输入责任人姓名" />
        </el-form-item>

            <el-form-item label="责任人身份证号" prop="responsibleIdcard">
              <el-input v-model="resourceForm.responsibleIdcard" placeholder="请输入责任人身份证号" />
        </el-form-item>


            <el-form-item label="责任人手机号" prop="responsiblePhone">
              <el-input v-model="resourceForm.responsiblePhone" placeholder="请输入责任人手机号" />
            </el-form-item>


            <el-form-item label="责任人身份证正面" prop="responsibleIdcardFront">
            <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleResponsibleFrontSuccess"
                :file-list="responsibleFrontFileList"
                :headers="headers"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
            </el-upload>
        </el-form-item>


            <el-form-item label="责任人身份证背面" prop="responsibleIdcardBack">
          <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleResponsibleBackSuccess"
                :file-list="responsibleBackFileList"
                :headers="headers"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
            </el-form-item>

          </el-tab-pane>
          <!--          <el-tab-pane label="授权委托书" name="other">-->
          <!--&lt;!&ndash;            <el-form-item label="生效签名范围" prop="authorizedSignatures">&ndash;&gt;-->
          <!--&lt;!&ndash;              <el-input v-model="form.authorizedSignatures" type="textarea" :rows="4" placeholder="请输入生效签名范围" />&ndash;&gt;-->
          <!--&lt;!&ndash;            </el-form-item>&ndash;&gt;-->
          <!--          </el-tab-pane>-->
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量上传对话框 -->
    <el-dialog
      title="批量资质补录"
      :visible.sync="batchUploadVisible"
      width="600px"
      custom-class="custom-dialog"
    >
      <div class="batch-upload-content">
        <el-upload
          class="batch-upload custom-upload"
          drag
          action="#"
          :http-request="handleBatchQualificationUpload"
          :on-change="handleBatchFileChange"
          :on-remove="handleBatchFileRemove"
          :file-list="batchFileList"
          :auto-upload="false"
          :limit="10"
          multiple
          accept=".zip,.rar,.7z"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">支持ZIP、RAR、7Z格式压缩包，单个文件不超过50MB</div>
        </el-upload>

        <div class="batch-upload-tips">
          <p>批量上传说明：</p>
          <p>1. 请将资质材料按照签名名称分别放入不同文件夹</p>
          <p>2. 每个文件夹内放入对应的资质材料，并确保文件名清晰明了</p>
          <p>3. 将所有文件夹打包成压缩包后上传</p>
          <p>4. <a href="javascript:;" @click="downloadBatchTemplate">下载批量上传模版</a></p>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="batchUploadVisible = false" class="custom-button">取 消</el-button>
        <el-button type="primary" @click="confirmBatchUpload" :disabled="batchFileList.length === 0" class="custom-button primary-button">上 传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSignatures, getSignatures, delSignatures, addSignatures, updateSignatures } from "@/api/Sms/signatures";
import { listCertification, getCertification, delCertification, addCertification, updateCertification } from '@/api/Sms/certification'
import { getToken } from "@/utils/auth";
export default {
  name: 'SmsSignature',
  dicts: ["audit_status","signature_type","biz_license_type"],
  data() {
    return {
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 上传头部
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 选中的消息组
      selectedGroup: 'marketing',

      // 当前活动标签页
      activeTab: 'signature',
      activeTabcCert: 'editCert',
      // 筛选条件 - 签名管理
      signatureFilter: 'all',
      searchQuery: '',

      // 筛选条件 - 资质管理
      resourceSearchQuery: '',
      resourceTypeFilter: '',
      responsiblePersonFilter: '',
      auditStatusFilter: '',
      signatureTypeFilter: '',

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 资质管理分页
      currentPage2: 1,
      pageSize2: 10,
      total2: 0,

      // 签名列表
      signatures: [],

      // 资质列表
      certificationList: [
      ],
      // 详情弹窗
      detailOpen: false,
      // 详情数据
      detail: {},
      // 对话框
      signatureDialogVisible: false,
      resourceDialogVisible: false,
      batchUploadVisible: false,

      // 签名表单
      signatureForm: {
        signatureId: '', // 编辑时使用
        signatureName: '',
        signatureType: '',
        signatureContent: '',
        purposeDescription: '',
        websiteUrl: '',
        certificationId: ''
      },

      // 签名表单验证规则
      signatureRules: {
        signatureName: [
          { required: true, message: '请输入签名名称', trigger: 'blur' }
        ],
        signatureType: [
          { required: true, message: '请选择签名类型', trigger: 'change' }
        ],
        signatureContent: [
          { required: true, message: '请输入签名内容', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        purposeDescription: [
          { required: true, message: '请输入用途描述', trigger: 'blur' }
        ],
        websiteUrl: [
          { required: true, message: '请输入网站地址', trigger: 'blur' }
        ],
        certificationId: [
          { required: true, message: '请选择资质', trigger: 'change' }
        ]
      },

      // 资质表单
      resourceForm: {

      },

      // 资质表单验证规则
      resourceRules: {
        enterpriseName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        qualificationName: [
          { required: true, message: "资质名称不能为空", trigger: "blur" }
        ],
        bizLicenseType: [
          { required: true, message: "营业证件类型不能为空", trigger: "change" }
        ],
        bizLicenseNumber: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" },
          {
            pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/,
            message: "请输入正确的18位统一社会信用代码",
            trigger: "blur"
          }
        ],
        legalPersonName: [
          { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        legalPersonIdcard: [
          { required: true, message: "法人身份证号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的18位身份证号",
            trigger: "blur"
          }
        ],
        operatorName: [
          { required: true, message: "经办人姓名不能为空", trigger: "blur" }
        ],
        operatorIdcard: [
          { required: true, message: "经办人身份证号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的18位身份证号",
            trigger: "blur"
          }
        ],
        operatorPhone: [
          { required: true, message: "经办人手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的11位手机号",
            trigger: "blur"
          }
        ],
        responsibleName: [
          { required: true, message: "责任人姓名不能为空", trigger: "blur" }
        ],
        responsibleIdcard: [
          { required: true, message: "责任人身份证号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的18位身份证号",
            trigger: "blur"
          }
        ],
        responsiblePhone: [
          { required: true, message: "责任人手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的11位手机号",
            trigger: "blur"
          }
        ],
        bizLicenseImage: [
          { required: true, message: "营业执照不能为空", trigger: "blur" }
        ],
        responsibleIdcardFront: [
          { required: true, message: "责任人身份证正面不能为空", trigger: "blur" }
        ],
        responsibleIdcardBack: [
          { required: true, message: "责任人身份证反面不能为空", trigger: "blur" }
        ],
        operatorIdcardFront: [
          { required: true, message: "经办人身份证正面不能为空", trigger: "blur" }
        ],
        operatorIdcardBack: [
          { required: true, message: "经办人身份证反面不能为空", trigger: "blur" }
        ],
      },

      // 上传文件列表
      licenseFiles: [],
      idFrontFiles: [],
      idBackFiles: [],
      responsibleIdFrontFiles: [],
      responsibleIdBackFiles: [],
      authorizationFiles: [],
      otherFiles: [],
      additionalFiles: [],
      batchFileList: [],
      bizLicenseFileList: [],
      operatorFrontFileList: [],
      operatorBackFileList: [],
      responsibleFrontFileList: [],
      responsibleBackFileList: [],


      // 对话框部分折叠状态控制
      expandedSections: {
        basicInfo: false,
        enterpriseInfo: false,
        operatorInfo: false,
        responsibleInfo: false,
        authorizationInfo: false,
        otherMaterials: false
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        smsName: null,
        enterpriseName: null,
        qualificationName: null,
        auditStatus: null,
        bizLicenseNumber: null,
        legalPersonName: null,
        operatorName: null,
        responsibleName: null,
        userId: null

      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        smsName: null,
        enterpriseName: null,
        qualificationName: null,
        auditStatus: null,
        bizLicenseNumber: null,
        legalPersonName: null,
        operatorName: null,
        responsibleName: null,
        userId: null
      },
      formMode: 'add',
      loading: false,

      // 资质表单模式：'add', 'edit', 'view', 'reapply'
      resourceFormMode: 'add',
    }
  },
  computed: {
    // 表格样式
    tableHeaderStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 500,
        height: '50px'
      }
    }
  },
  created() {
    this.queryParams1.userId = this.$store.state.user.userId;
    this.queryParams2.userId = this.$store.state.user.userId;
    this.getSignaturesList();
    this.getCertificationList();
  },
  methods: {
    getSignaturesList() {
      this.loading = true;
      listSignatures(this.queryParams1).then(response => {
        if (response.code === 200) {
          this.signatures = response.rows || [];
          this.total = response.total || 0;
        } else {
          this.signatures = [];
          this.total = 0;
          this.$message.error(response.msg || '获取签名列表失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取签名列表出错:', error);
        this.signatures = [];
        this.total = 0;
        this.loading = false;
        this.$message.error('获取签名列表失败');
      });
    },

    /** 搜索按钮操作 */
    handleQuery1() {
      this.queryParams1.pageNum = 1;
      this.getSignaturesList();
    },

    getCertificationList() {
      this.loading = true;
      listCertification(this.queryParams2).then(response => {
        if (response.code === 200) {
          this.certificationList = response.rows || [];
          if (response.total) {
            this.total2 = response.total;
          }
        } else {
          this.certificationList = [];
          this.$message.error(response.msg || '获取资质列表失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取资质列表出错:', error);
        this.certificationList = [];
        this.loading = false;
        this.$message.error('获取资质列表失败');
      });
    },
    handleQuery2() {
      this.queryParams2.pageNum = 1;
      this.getCertificationList();
    },
    // 获取状态标签样式
    getStatusType(status) {
      const types = {
        'successful': 'success',
        'rejected': 'danger',
        'pending': 'warning'
      };
      return types[status] || 'info';
    },

    // 查看签名
    handleViewSignature(row) {
      this.loading = true;
      getSignatures(row.signatureId).then(response => {
        if (response.code === 200) {
          // 显示签名详情
          this.signatureForm = response.data;
          this.signatureDialogVisible = true;
          // 只读模式 - 你可以添加一个mode属性控制表单只读
          this.formMode = 'view';
        } else {
          this.$message.error(response.msg || '获取签名详情失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取签名详情失败:', error);
        this.$message.error('获取签名详情失败');
        this.loading = false;
      });
    },

    // 复制签名
    handleCopySignature(row) {
      this.loading = true;
      getSignatures(row.signatureId).then(response => {
        if (response.code === 200) {
          const signature = response.data;
          this.signatureForm = {
            signatureName: signature.signatureName + ' - 副本',
            signatureType: signature.signatureType,
            signatureContent: signature.signatureContent,
            purposeDescription: signature.purposeDescription,
            websiteUrl: signature.websiteUrl,
            certificationId: signature.certificationId
          };
          this.signatureDialogVisible = true;
          this.formMode = 'add';
          this.$message.success('已复制签名，请修改后提交');
        } else {
          this.$message.error(response.msg || '复制签名失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('复制签名失败:', error);
        this.$message.error('复制签名失败');
        this.loading = false;
      });
    },

    // 删除签名
    handleDeleteSignature(row) {
      this.$confirm(`确定要删除签名"${row.signatureContent}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        delSignatures(row.signatureId).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功!');
            this.getSignaturesList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '删除失败');
          }
          this.loading = false;
        }).catch(error => {
          console.error('删除签名失败:', error);
          this.$message.error('删除签名失败');
          this.loading = false;
        });
      }).catch(() => {
        // 取消删除
      });
    },

    // 创建签名
    handleCreateSignature() {
      this.signatureForm = {
        signatureName: '',
        signatureType: '',
        signatureContent: '',
        purposeDescription: '',
        websiteUrl: '',
        certificationId: ''
      };
      this.additionalFiles = [];
      this.signatureDialogVisible = true;
      this.formMode = 'add';
    },

    // 提交签名表单
    submitSignatureForm() {
      this.$refs.signatureForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          // 准备提交数据
          const formData = {
            signatureId: this.signatureForm.signatureId,
            signatureName: this.signatureForm.signatureName,
            signatureType: this.signatureForm.signatureType,
            signatureContent: this.signatureForm.signatureContent,
            purposeDescription: this.signatureForm.purposeDescription,
            websiteUrl: this.signatureForm.websiteUrl,
            certificationId: this.signatureForm.certificationId,
            userId: this.$store.state.user.userId
          };

          // 根据模式决定是新增还是更新
          const request = this.formMode === 'add' ?
                          addSignatures(formData) :
                          updateSignatures(formData);

          request.then(response => {
            if (response.code === 200) {
              this.$message.success(this.formMode === 'add' ? '添加成功!' : '更新成功!');
          this.signatureDialogVisible = false;
              this.getSignaturesList(); // 刷新列表
            } else {
              this.$message.error(response.msg || (this.formMode === 'add' ? '添加失败!' : '更新失败!'));
            }
            this.loading = false;
          }).catch(error => {
            console.error(this.formMode === 'add' ? '添加签名失败:' : '更新签名失败:', error);
            this.$message.error(this.formMode === 'add' ? '添加签名失败!' : '更新签名失败!');
            this.loading = false;
          });
        }
      });
    },

    // 查看资质详情
    handleViewResource(row) {
      this.loading = true;
      this.bizLicenseFileList = [];
      this.operatorFrontFileList = [];
      this.operatorBackFileList = [];
      this.responsibleFrontFileList = [];
      this.responsibleBackFileList = [];
      this.activeTabcCert = 'base';
      getCertification(row.applyId).then(response => {
        if (response.code === 200) {
          // 显示资质详情
          this.resourceForm = response.data;
          if (this.resourceForm.bizLicenseType === null || this.resourceForm.bizLicenseType === undefined) {
            this.resourceForm.bizLicenseType = 'business_license';
          }
          // 设置折叠区域为展开状态以便查看
          Object.keys(this.expandedSections).forEach(key => {
            this.expandedSections[key] = true;
          });

          this.resourceDialogVisible = true;
          // 只读模式
          this.resourceFormMode = 'view';

          // 加载已有图片到对应的文件列表
          if (this.resourceForm.bizLicenseImage) {
            this.bizLicenseFileList = [{
              name: '营业执照',
              url: this.baseUrl + this.resourceForm.bizLicenseImage
            }];
          }
          if (this.resourceForm.operatorIdcardFront) {
            this.operatorFrontFileList = [{
              name: '经办人身份证正面',
              url: this.baseUrl + this.resourceForm.operatorIdcardFront
            }];
          }
          if (this.resourceForm.operatorIdcardBack) {
            this.operatorBackFileList = [{
              name: '经办人身份证背面',
              url: this.baseUrl + this.resourceForm.operatorIdcardBack
            }];
          }
          if (this.resourceForm.responsibleIdcardFront) {
            this.responsibleFrontFileList = [{
              name: '责任人身份证正面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardFront
            }];
          }
          if (this.resourceForm.responsibleIdcardBack) {
            this.responsibleBackFileList = [{
              name: '责任人身份证背面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardBack
            }];
          }
        } else {
          this.$message.error(response.msg || '获取资质详情失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取资质详情失败:', error);
        this.$message.error('获取资质详情失败');
        this.loading = false;
      });
    },
    /** 查看详情 */
    handleDetail(row) {
      this.detail = Object.assign({}, row);
      this.detailOpen = true;
    },
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal.confirm('是否确认删除资质认证编号为"' + applyIds + '"的数据项？').then(function() {
        return delCertification(applyIds);
      }).then(() => {
        this.getCertificationList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 取消详情对话框
    cancelDetail() {
      this.detailOpen = false;
    },

    // 详情对话框关闭后的回调
    handleDetailClosed() {
      this.detail = {};
    },
    // 快速复制资质
    handleQuickCopy(row) {
      this.loading = true;
      this.bizLicenseFileList = [];
      this.operatorFrontFileList = [];
      this.operatorBackFileList = [];
      this.responsibleFrontFileList = [];
      this.responsibleBackFileList = [];
      this.activeTabcCert = 'base';
      getCertification(row.applyId).then(response => {
        if (response.code === 200) {

          this.resourceForm = response.data;
          this.resourceForm.applyId=null;
          if (this.resourceForm.bizLicenseType === null || this.resourceForm.bizLicenseType === undefined) {
            this.resourceForm.bizLicenseType = 'business_license';
          }
          // 设置所有区域为展开状态
          Object.keys(this.expandedSections).forEach(key => {
            this.expandedSections[key] = true;
          });

          this.resourceDialogVisible = true;
          this.resourceFormMode = 'add';
          // 加载已有图片到对应的文件列表
          if (this.resourceForm.bizLicenseImage) {
            this.bizLicenseFileList = [{
              name: '营业执照',
              url: this.baseUrl + this.resourceForm.bizLicenseImage
            }];
          }
          if (this.resourceForm.operatorIdcardFront) {
            this.operatorFrontFileList = [{
              name: '经办人身份证正面',
              url: this.baseUrl + this.resourceForm.operatorIdcardFront
            }];
          }
          if (this.resourceForm.operatorIdcardBack) {
            this.operatorBackFileList = [{
              name: '经办人身份证背面',
              url: this.baseUrl + this.resourceForm.operatorIdcardBack
            }];
          }
          if (this.resourceForm.responsibleIdcardFront) {
            this.responsibleFrontFileList = [{
              name: '责任人身份证正面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardFront
            }];
          }
          if (this.resourceForm.responsibleIdcardBack) {
            this.responsibleBackFileList = [{
              name: '责任人身份证背面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardBack
            }];
          }
          this.$message.success('已复制资质信息，请修改后提交');
        } else {
          this.$message.error(response.msg || '复制资质失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('复制资质失败:', error);
        this.$message.error('复制资质失败');
        this.loading = false;
      });
    },

    // 重新申请资质
    handleReapplyResource(row) {
      this.loading = true;
      this.bizLicenseFileList = [];
      this.operatorFrontFileList = [];
      this.operatorBackFileList = [];
      this.responsibleFrontFileList = [];
      this.responsibleBackFileList = [];
      this.activeTabcCert = 'base';
      this.loading = true;
      getCertification(row.applyId).then(response => {
        if (response.code === 200) {
          this.resourceForm = response.data;
          if (this.resourceForm.bizLicenseType === null || this.resourceForm.bizLicenseType === undefined) {
            this.resourceForm.bizLicenseType = '0';
          }
          // 设置所有区域为展开状态
          Object.keys(this.expandedSections).forEach(key => {
            this.expandedSections[key] = true;
          });

          this.resourceDialogVisible = true;
          this.resourceFormMode = 'edit';
          // 加载已有图片到对应的文件列表
          if (this.resourceForm.bizLicenseImage) {
            this.bizLicenseFileList = [{
              name: '营业执照',
              url: this.baseUrl + this.resourceForm.bizLicenseImage
            }];
          }
          if (this.resourceForm.operatorIdcardFront) {
            this.operatorFrontFileList = [{
              name: '经办人身份证正面',
              url: this.baseUrl + this.resourceForm.operatorIdcardFront
            }];
          }
          if (this.resourceForm.operatorIdcardBack) {
            this.operatorBackFileList = [{
              name: '经办人身份证背面',
              url: this.baseUrl + this.resourceForm.operatorIdcardBack
            }];
          }
          if (this.resourceForm.responsibleIdcardFront) {
            this.responsibleFrontFileList = [{
              name: '责任人身份证正面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardFront
            }];
          }
          if (this.resourceForm.responsibleIdcardBack) {
            this.responsibleBackFileList = [{
              name: '责任人身份证背面',
              url: this.baseUrl + this.resourceForm.responsibleIdcardBack
            }];
          }
        }
        this.loading = false;
      }).catch(error => {
        console.error('重新申请资质失败:', error);
        this.$message.error('重新申请资质失败');
        this.loading = false;
      });
    },


    // 附加文件上传
    handleFileUpload(options) {
      this.additionalFiles.push({ name: options.file.name, url: URL.createObjectURL(options.file) });
    },

    // 附加文件移除
    handleFileRemove(file, fileList) {
      this.additionalFiles = fileList;
    },



    // 批量文件变更
    handleBatchFileChange(file, fileList) {
      this.batchFileList = fileList;
    },

    // 批量文件移除
    handleBatchFileRemove(file, fileList) {
      this.batchFileList = fileList;
    },

    // 批量资质上传
    handleBatchQualificationUpload(options) {
      console.log('批量上传资质:', options.file);
      // 这里应该是实际的文件上传逻辑
    },

    // 确认批量上传
    confirmBatchUpload() {
      if (this.batchFileList.length === 0) {
        this.$message.warning('请先选择文件');
        return;
      }

      // 模拟上传过程
      this.$message({
        message: '正在上传资质...',
        type: 'info'
      });

      setTimeout(() => {
        this.$message({
          message: '批量上传成功',
          type: 'success'
        });

        this.batchUploadVisible = false;
      }, 2000);
    },

    // 下载批量上传模版
    downloadBatchTemplate() {
      this.$message({
        message: '模版下载中...',
        type: 'info'
      });

      setTimeout(() => {
        this.$message({
          message: '模版下载成功',
          type: 'success'
        });
      }, 1000);
    },

    // 分页
    handleSizeChange(val) {
      if (this.activeTab === 'signature') {
        this.pageSize = val;
        this.queryParams1.pageSize = val;
        this.getSignaturesList();
      } else {
        this.pageSize2 = val;
        this.queryParams2.pageSize = val;
        this.getCertificationList();
      }
    },
    handleCurrentChange(val) {
      if (this.activeTab === 'signature') {
        this.currentPage = val;
        this.queryParams1.pageNum = val;
        this.getSignaturesList();
      } else {
        this.currentPage2 = val;
        this.queryParams2.pageNum = val;
        this.getCertificationList();
      }
    },

    // 切换部分的展开/折叠
    toggleSection(section) {
      this.expandedSections[section] = !this.expandedSections[section];
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      // 如果已经是格式化好的日期时间字符串，直接返回
      if (dateTimeStr.includes(' ')) return dateTimeStr;

      try {
        const date = new Date(dateTimeStr);
        return date.getFullYear() + '-' +
               String(date.getMonth() + 1).padStart(2, '0') + '-' +
               String(date.getDate()).padStart(2, '0') + ' ' +
               String(date.getHours()).padStart(2, '0') + ':' +
               String(date.getMinutes()).padStart(2, '0') + ':' +
               String(date.getSeconds()).padStart(2, '0');
      } catch (e) {
        return dateTimeStr;
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'successful': '审核通过',
        'rejected': '审核拒绝',
        'pending': '审核中'
      };
      return statusMap[status] || status;
    },

    // 获取营业执照类型文本
    getLicenseTypeText(type) {
      const typeMap = {
        'business_license': '企业营业执照',
        'social_code': '社会信用代码证书',
        'organization_license': '事业单位法人证书'
      };
      return typeMap[type] || type;
    },

    // 创建资质
    handleCreateResource() {

      // 设置新增模式
      // 初始化表单数据
      this.resourceForm = {
        userId: this.$store.state.user.userId,
        smsName: this.$store.state.user.nickname,
        applyId: null,
        enterpriseName: null,
        qualificationName: null,
        auditStatus: 'pending',
        createdAt: null,
        updatedAt: null,
        bizLicenseType: 'business_license',
        bizLicenseNumber: null,
        legalPersonName: null,
        legalPersonIdcard: null,
        operatorName: null,
        operatorIdcard: null,
        operatorPhone: null,
        responsibleName: null,
        responsibleIdcard: null,
        responsiblePhone: null,
        authorizedSignatures: null,
        bizLicenseImage: null,
        operatorIdcardFront: null,
        operatorIdcardBack: null,
        responsibleIdcardFront: null,
        responsibleIdcardBack: null
      };
      this.bizLicenseFileList = [];
      this.operatorFrontFileList = [];
      this.operatorBackFileList = [];
      this.responsibleFrontFileList = [];
      this.responsibleBackFileList = [];
      this.resetForm("resourceForm");
      this.activeTabcCert = 'base';
      this.resourceDialogVisible = true;
      this.title = "添加资质认证";
    },
    /** 提交按钮 */
    submitForm() {
      this.resourceForm.userId = this.$store.state.user.userId;
      this.resourceForm.smsName = this.$store.state.user.nickname;
      console.log(this.$store.state.user.nickname);
      console.log(this.resourceForm);

    this.$refs.resourceForm.validate(valid => {
        if (valid) {
          if (this.resourceForm.applyId != null) {
            updateCertification(this.resourceForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resourceDialogVisible = false;
              this.getCertificationList();
            });
          } else {
            addCertification(this.resourceForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resourceDialogVisible = false;
              this.getCertificationList();
            });
          }
        }
      });
    },
    // 表单关闭前的处理方法
    handleClose(done) {
      this.$nextTick(() => {
        this.resourceDialogVisible = false;
        // 使用宏任务延迟处理，避免与Vue更新周期冲突
        setTimeout(() => {
          if (done) done();
          this.handleDialogClosed();
        }, 200);
      });
    },
    // 对话框完全关闭后的回调
    handleDialogClosed() {
      this.resetForm("resourceForm");
      this.resourceForm = {
        applyId: null,
        enterpriseName: null,
        qualificationName: null,
        auditStatus: 'pending',
        createdAt: null,
        updatedAt: null,
        bizLicenseType: '0',
        bizLicenseNumber: null,
        legalPersonName: null,
        legalPersonIdcard: null,
        operatorName: null,
        operatorIdcard: null,
        operatorPhone: null,
        responsibleName: null,
        responsibleIdcard: null,
        responsiblePhone: null,
        authorizedSignatures: null,
        bizLicenseImage: null,
        operatorIdcardFront: null,
        operatorIdcardBack: null,
        responsibleIdcardFront: null,
        responsibleIdcardBack: null
      };
      this.bizLicenseFileList = [];
      this.operatorFrontFileList = [];
      this.operatorBackFileList = [];
      this.responsibleFrontFileList = [];
      this.responsibleBackFileList = [];
      this.activeTabcCert = 'base';
    },
    // 上传图片预览
    handlePreview(file) {
      window.open(file.url);
    },

    // 上传图片删除
    handleRemove(file, fileList) {
      const fileName = file.name || file.response.fileName;
      const fileUrl = file.url || (file.response && file.response.url);

      // 根据当前的操作类型删除对应的图片
      if (fileUrl === this.resourceForm.bizLicenseImage) {
        this.resourceForm.bizLicenseImage = '';
        this.bizLicenseFileList = fileList;
      } else if (fileUrl === this.resourceForm.operatorIdcardFront) {
        this.resourceForm.operatorIdcardFront = '';
        this.operatorFrontFileList = fileList;
      } else if (fileUrl === this.resourceForm.operatorIdcardBack) {
        this.resourceForm.operatorIdcardBack = '';
        this.operatorBackFileList = fileList;
      } else if (fileUrl === this.resourceForm.responsibleIdcardFront) {
        this.resourceForm.responsibleIdcardFront = '';
        this.responsibleFrontFileList = fileList;
      } else if (fileUrl === this.resourceForm.responsibleIdcardBack) {
        this.resourceForm.responsibleIdcardBack = '';
        this.responsibleBackFileList = fileList;
      }
    },

    // 营业执照上传成功
    handleBizLicenseSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.resourceForm.bizLicenseImage = response.fileName;
        this.$message.success("营业执照上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        // 移除上传失败的文件
        fileList.splice(fileList.indexOf(file), 1);
      }
      this.bizLicenseFileList = fileList;
    },

    // 经办人身份证正面上传成功
    handleOperatorFrontSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.resourceForm.operatorIdcardFront = response.fileName;
        this.$message.success("经办人身份证正面上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        // 移除上传失败的文件
        fileList.splice(fileList.indexOf(file), 1);
      }
      this.operatorFrontFileList = fileList;
    },

    // 经办人身份证背面上传成功
    handleOperatorBackSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.resourceForm.operatorIdcardBack = response.fileName;
        this.$message.success("经办人身份证背面上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        // 移除上传失败的文件
        fileList.splice(fileList.indexOf(file), 1);
      }
      this.operatorBackFileList = fileList;
    },

    // 责任人身份证正面上传成功
    handleResponsibleFrontSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.resourceForm.responsibleIdcardFront = response.fileName;
        this.$message.success("责任人身份证正面上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        // 移除上传失败的文件
        fileList.splice(fileList.indexOf(file), 1);
      }
      this.responsibleFrontFileList = fileList;
    },

    // 责任人身份证背面上传成功
    handleResponsibleBackSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.resourceForm.responsibleIdcardBack = response.fileName;
        this.$message.success("责任人身份证背面上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        // 移除上传失败的文件
        fileList.splice(fileList.indexOf(file), 1);
      }
      this.responsibleBackFileList = fileList;
    },

    // 验证数据结构
    validateCertificationData() {
      if (this.certificationList && this.certificationList.length > 0) {
        const sample = this.certificationList[0];
        console.group('资质数据验证');
        console.log('样本数据:', sample);
        console.log('法人姓名字段存在:', 'legalPersonName' in sample);
        console.log('经办人姓名字段存在:', 'operatorName' in sample);
        console.log('责任人姓名字段存在:', 'responsibleName' in sample);
        console.log('法人姓名值:', sample.legalPersonName);
        console.log('经办人姓名值:', sample.operatorName);
        console.log('责任人姓名值:', sample.responsibleName);
        console.groupEnd();
      }
    },
  },
  mounted() {
    // 移除导致错误的代码
    // this.total = this.resources.length; // 这行代码是错误的来源

    // 改为仅在有数据时进行操作
    if (this.signatures && this.signatures.length) {
      this.total = this.signatures.length;
    }

    // 如果certificationList有数据则使用
    if (this.certificationList && this.certificationList.length) {
      // 可以在这里处理certificationList相关逻辑
    }
  }
}
</script>

<style scoped>
.sms-signature-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 22px;
  color: #303133;
  margin: 0;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
}

/* 信息提示条样式 */
.info-alert {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 标签页样式 */
.tab-container {
  margin-bottom: 20px;
}

.custom-tabs >>> .el-tabs__item {
  font-size: 15px;
  height: 50px;
  line-height: 50px;
}

.custom-tabs >>> .el-tabs__active-bar {
  height: 3px;
}

/* 签名管理说明 */
.signature-instructions {
  background-color: #f5f7fa;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.signature-instructions ol {
  margin: 0;
  padding-left: 20px;
}

.signature-instructions li {
  margin-bottom: 10px;
  color: #606266;
  line-height: 1.5;
}

.signature-instructions li:last-child {
  margin-bottom: 0;
}

.link-text {
  color: #409eff;
  text-decoration: none;
}

/* 筛选工具栏样式 */
.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.left-section {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.right-section {
  display: flex;
  gap: 10px;
}

/* 自定义表单控件样式 */
.custom-input >>> .el-input__inner {
  border-radius: 4px;
  height: 40px;
  transition: all 0.3s;
}

.custom-input >>> .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 159, 255, 0.2);
}

.custom-select >>> .el-input__inner {
  border-radius: 4px;
  height: 40px;
}

.custom-textarea >>> .el-textarea__inner {
  border-radius: 4px;
  transition: all 0.3s;
}

.custom-textarea >>> .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 159, 255, 0.2);
}

/* 自定义按钮样式 */
.custom-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.primary-button {
  background-color: #409eff;
  border-color: #409eff;
}

.primary-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 自定义表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.custom-table >>> .el-table__header-wrapper th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
}

.custom-table >>> .el-table__row:hover {
  background-color: #f5f7fa;
}

/* 自定义标签样式 */
.custom-tag {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

/* 操作按钮样式 */
.action-button {
  color: #409eff;
  margin-right: 10px;
  padding: 2px 0;
  border: none;
  background: none;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  font-size: 12px;
  min-width: auto;
}

.action-button:hover {
  color: #66b1ff;
  background: none;
  border: none;
  text-decoration: underline;
}

.action-button:focus {
  outline: none;
  color: #66b1ff;
}

.action-button:active {
  color: #3a8ee6;
}

/* 表格操作列样式 */
.custom-table >>> .el-table__fixed-right {
  z-index: 10;
}

.custom-table >>> .el-table__body-wrapper {
  overflow-x: auto;
}

.custom-table >>> .el-table__row .el-table__cell:last-child {
  padding: 8px 12px;
}

.custom-table >>> .el-table__row .el-table__cell:last-child .cell {
  white-space: nowrap;
  overflow: visible;
}

/* 空数据状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.empty-image {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.empty-text {
  color: #909399;
  font-size: 14px;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

.custom-pagination >>> .el-pagination__total,
.custom-pagination >>> .el-pagination__jump {
  margin-left: 16px;
}

.custom-pagination >>> .el-pagination__sizes {
  margin-left: 16px;
}

.custom-pagination >>> .el-pagination button {
  min-width: 32px;
  height: 32px;
}

.custom-pagination >>> .el-pager li {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

/* 表格底部信息 */
.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.page-info {
  color: #606266;
  font-size: 14px;
}

/* 对话框样式 */
.custom-dialog >>> .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog >>> .el-dialog__title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.custom-dialog >>> .el-dialog__body {
  padding: 20px;
}

.custom-dialog >>> .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 20px 0 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 20px 0 15px;
}

/* 上传区域样式 */
.upload-box, .auth-upload-box {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-trigger:hover {
  border-color: #409eff;
}

.upload-trigger i {
  font-size: 28px;
  color: #8c939d;
}

.upload-trigger p {
  margin: 10px 0 0;
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.id-upload-container {
  display: flex;
  gap: 20px;
}

.id-upload-box {
  width: 150px;
  height: 150px;
}

.custom-upload >>> .el-upload-list__item {
  transition: all 0.3s;
}

.custom-upload >>> .el-upload-list__item:hover {
  background-color: #f5f7fa;
}

/* 验证按钮 */
.verification-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.verify-button {
  color: #409eff;
  font-weight: 500;
}

.info-button {
  margin-left: 10px;
  color: #909399;
}

/* 其他材料 */
.other-materials {
  margin-top: 15px;
}

.materials-label {
  margin-bottom: 10px;
  color: #606266;
}

/* 批量上传对话框样式 */
.batch-upload-content {
  margin-bottom: 20px;
}

.batch-upload {
  width: 100%;
}

.batch-upload >>> .el-upload-dragger {
  width: 100%;
  height: 180px;
  border-radius: 6px;
  transition: all 0.3s;
}

.batch-upload >>> .el-upload-dragger:hover {
  border-color: #409eff;
}

.batch-upload >>> .el-upload-dragger i {
  font-size: 40px;
  margin-bottom: 10px;
}

.batch-upload >>> .el-upload__text {
  font-size: 16px;
}

.batch-upload >>> .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.batch-upload-tips {
  margin-top: 20px;
  font-size: 12px;
  color: #606266;
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  line-height: 1.5;
}

.batch-upload-tips p {
  margin: 4px 0;
}

.batch-upload-tips a {
  color: #409eff;
  text-decoration: none;
}

/* 响应式样式 */
@media screen and (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
  }

  .filter-toolbar {
    flex-direction: column;
    align-items: flex-start;
  }

  .left-section, .right-section {
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .sms-signature-container {
    padding: 10px;
  }

  .id-upload-container {
    flex-direction: column;
  }
}

/* 可折叠部分样式 */
.collapsible-section {
  margin-bottom: 16px;
}

.section-header {
  cursor: pointer;
}

.dialog-section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 20px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.dialog-section-title i {
  margin-right: 8px;
  transition: transform 0.3s;
}

.dialog-section-title i.is-expanded {
  transform: rotate(90deg);
}

.section-content {
  padding-left: 8px;
  transition: all 0.3s;
}
</style>
